<template>
  <BasicModal v-bind="$attrs" @register="registerDrawer" destroyOnClose :title="title" :width="'70%'" @ok="handleSubmit">
    <BasicForm @register="registerForm" name="UfMallFreightFeeIncludedRuleForm">
      <template #deliveryAreas="{ model, field }">
        <a-cascader
          v-model:value="deliveryAreas"
          @change="
            (e) => {
              model[field] = e;
            }
          "
          :options="regionData"
          multiple
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { saveOrUpdateFeeIncludedRule, saveOrUpdateFeeRule } from "../UfMallFreightTemplate.api";
  import { regionData } from '@/components/Form/src/utils/areaDataUtil';
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const isDetail = ref(false);
  const templateId = ref('');
  const deliveryAreas = ref<any>([]);

  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, scrollToField, updateSchema }] = useForm({
    labelWidth: 150,
    schemas: [
      {
        label: '地区',
        field: 'deliveryAreas',
        component: 'Cascader',
        required: true,
        componentProps: {
          multiple: true,
          options: regionData,
          getPopupContainer: () => {
            return document.body;
          },
        },
        slot: 'deliveryAreas',
      },
      {
        label: '类型',
        field: 'includedType',
        component: 'JDictSelectTag',
        required: true,
        componentProps: {
          style: 'width:100%',
          dictCode: 'included_type',
          getPopupContainer: () => {
            return document.body;
          },
        },
      },
      {
        label: '小于件/体积/重量',
        field: 'reachData',
        component: 'InputNumber',
        required: true,
        componentProps: {
          style: 'width:100%',
          addonAfter: '件（个）/体积（m³）/重量（kg）',
        },
        ifShow: function ({ model }) {
          console.log(model.includedType);
          return model.includedType == 'REACH_DATA_AND_AMOUNT' || model.includedType == 'ONLY_REACH_DATA';
        },
      },
      {
        label: '满金额',
        field: 'reachAmount',
        component: 'InputNumber',
        required: true,
        componentProps: {
          style: 'width:100%',
          addonAfter: '元',
        },
        ifShow: function ({ model }) {
          return model.includedType == 'REACH_DATA_AND_AMOUNT' || model.includedType == 'ONLY_REACH_AMOUNT';
        },
      },
      {
        label: '',
        field: 'templateId',
        component: 'Input',
        show: false,
      },
      {
        label: '',
        field: 'id',
        component: 'Input',
        show: false,
      },
    ],
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });
  //表单赋值
  const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
    templateId.value = data.templateId;
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter, showFooter: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !!data?.showFooter;
    deliveryAreas.value = [];
    if (unref(isUpdate)) {
      //表单赋值
      let dataRecord = Object.assign({}, data.record);
      let tempDeliveryAreas = dataRecord.deliveryAreas.split(',');
      let aimDeliveryArea: any[] = [];
      for (let i = 0; i < tempDeliveryAreas.length; i++) {
        aimDeliveryArea.push(tempDeliveryAreas[i].split('|'));
      }
      deliveryAreas.value = aimDeliveryArea;
      await setFieldsValue({
        ...dataRecord,
      });
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(isDetail) ? '详情' : '编辑'));
  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      let tempDeliveryAreas: any[] = [];
      for (let i = 0; i < deliveryAreas.value.length; i++) {
        let deliveryArea: any[] = deliveryAreas.value[i];
        let joinedDeliveryArea: string = deliveryArea.join('|');
        tempDeliveryAreas.push(joinedDeliveryArea);
      }
      // 提交表单
      values.templateId = templateId.value;
      values.deliveryAreas = tempDeliveryAreas.join(',');
      await saveOrUpdateFeeIncludedRule(values);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less">
  #zwx-area-link .ant-select {
    width: 100% !important;
  }

  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
